package hotel.quartz.oversea.job.switchs;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.GsonUtils;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.job.task.JobSaveSwDelayLogTask;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class SwitchHotelRejectOrderCheckToBookingJob implements BaseJob {
    private String timestamp = "Shdoctbj"+String.valueOf(System.currentTimeMillis());

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    JobSaveSwDelayLogTask jobSaveSwDelayLogTask;

    /**
     *
     *  调整：20200729：增加系统状态：定时器查询延时单的系统状态为 0  1  2  10
     *
     *  延迟单 每一分钟跑处理方法   实时更新订单状态
     *
     *
     * @param jobExecutionContext
     */
    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("Switch Hotel Reject Order Check To Booking Job {} >>>>>>>> 携程实时跑状态为待确认的延迟单定时器执行时间: {}", timestamp, DateUtil.getNowTime());
        String host = CommonUrlConstants.SWITCHS_HOST;
        //携程接口，获取符合条件delay拒绝订单ids
        String getDelayRejectIdsUrl = host+ UrlSwitchsEnums.delayRejectToBooking.GET.getValue();
        //携程接口，通知处理该订单
        String dealRejectToBookingUrl = host+ UrlSwitchsEnums.delayRejectToBooking.RE_DEAL_ONE_ORDER_TO_POOL.getValue();
        List<String> idsList = requestDelayRejectOrderAll(getDelayRejectIdsUrl);
        if(null != idsList && idsList.size()>0){
            SendUtils.dingMsgNotLog("[DELAY-BOOKING]延时单程序判断继续下单采购 ", DateUtil.getCurrTime()+" 订单md5信息："+ GsonUtils.GsonString(idsList), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            log.info("Switch Hotel Reject Order Check To Booking Job {} >>>>>>>> 携程实时跑状态为待确认的延迟单定时器 idsList={},size={} ",timestamp, JSON.toJSONString(idsList),idsList.size());
            for (int i = 0; i <idsList.size() ; i++) {
                log.info("Switch Hotel Reject Order Check To Booking Job {} >>>>>>>> 携程实时跑状态为待确认的延迟单定时器 idsList.get(i)={} ,i={}",timestamp,idsList.get(i),i);
                requestDealToPoolHotel(dealRejectToBookingUrl,idsList.get(i));
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }else{
            log.info("Switch Hotel Reject Order Check To Booking Job {} >>>>>>>> 携程实时跑状态为待确认的延迟单定时器   未找到拒绝的延迟单 idsList is null ",timestamp);
        }
        log.info("Switch Hotel Reject Order Check To Booking Job {} >>>>>>>> 携程实时跑状态为待确认的延迟单定时器结束时间: {},{}",timestamp, DateUtil.getNowTime());
    }
    /**
     * 调处理一个订单至订单池定时器接口
     * @param url
     * @return
     */
    private void requestDealToPoolHotel(String url,String oneId) {
        Map map = new HashMap();
        map.put("md5key",oneId);//实际上是md5Key
        Result response = JobRestTemplateUtils.post(url, JSON.toJSONString(map),restTemplate);

        //保存日志
        jobSaveSwDelayLogTask.execute(oneId, JSON.toJSONString(response));

        if(response.getCode()!= CommonConstants.SUCCESS && null != response.getMsg() && response.getMsg().toString().contains("接口认证失败")){
            //当前母酒店携程实时跑状态为待确认的延迟单定时器为异常失败，让定时器下次进来再调起携程实时跑状态为待确认的延迟单定时器
        }else{
        }
        log.info("Switch Hotel Dealing Notify Order To Pool Job {} 携程实时跑状态为待确认的延迟单定时器信息进入方法 requestDealToPoolHotel 存在delay单每分钟查询 响应: map={},response={}",timestamp, JSON.toJSONString(map), JSON.toJSONString(response));
    }

    private List<String> requestDelayRejectOrderAll(String url) {
        Result response = JobRestTemplateUtils.post(url,null,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS && null != response.getMsg() && response.getMsg().toString().contains("接口认证失败")){
            //当前母酒店携程实时跑状态为待确认的延迟单定时器为异常失败，让定时器下次进来再调起携程实时跑状态为待确认的延迟单定时器
        }else{
            List<String> ids = (List<String>)response.getData();
            if(null != ids && ids.size()>0){
                return ids;
            }
        }
        return null;
    }

}
